//
//  HYPreviewImageScrollView.m
//  XPlayer
//
//  Created by 张水 on 2023/9/20.
//

#import "HYPreviewImageScrollView.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <HYUIKit/HYAlertShowAnimate.h>
#import <Photos/Photos.h>
#import "HYHub.h"
#define MaxScale 2.5  //最大缩放比例
#define MinScale 1.0  //最小缩放比例

@interface HYPreviewImageScrollView()<UIScrollViewDelegate>

@property (nonatomic ,strong) UIImageView *imageView;

@property (nonatomic ,copy) NSString *codeStr;

@end

@implementation HYPreviewImageScrollView

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame]){
        self.delegate = self;
        self.minimumZoomScale = MinScale;
        self.maximumZoomScale = MaxScale;
        self.backgroundColor = AppBgThemeColor;
        self.bounces = NO;
        
        self.imageView = [[UIImageView alloc]initWithFrame:self.frame];
        self.imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:self.imageView];
        //单击
        UITapGestureRecognizer *singleClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleClick:)];
        [self addGestureRecognizer:singleClick];
        //双击
        UITapGestureRecognizer *doubleClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleClick:)];
        doubleClick.numberOfTapsRequired = 2;
        [self addGestureRecognizer:doubleClick];
        
        [singleClick requireGestureRecognizerToFail:doubleClick];
        //添加长按手势
        UILongPressGestureRecognizer*longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(imglongTapClick:)];
        longTap.minimumPressDuration = 1;
        [self addGestureRecognizer:longTap];
    }
    return self;
}
- (void)setImagePath:(NSString *)imagePath
{
    if([imagePath containsString:@"http"]){
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:[UIImage imageNamed:@""]];
    }else{
        self.imageView.image = [UIImage imageWithContentsOfFile:imagePath];
    }
}

#pragma mark - UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView 
{
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    //重新获取center
    CGFloat offsetX = (self.bounds.size.width > self.contentSize.width) ? (self.bounds.size.width - self.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (self.bounds.size.height > self.contentSize.height) ? (self.bounds.size.height-self.contentSize.height) * 0.5 : 0.0;
    self.imageView.center = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX, scrollView.contentSize.height * 0.5 + offsetY);
}

//单击
- (void)singleClick:(UITapGestureRecognizer *)gestureRecognizer 
{
    if (self.HYPreViewdelegate &&[self.HYPreViewdelegate respondsToSelector:@selector(singleClickImageWith:)]) {
        [self.HYPreViewdelegate singleClickImageWith:self];
    }
}

//双击放大
- (void)doubleClick:(UITapGestureRecognizer *)gestureRecognizer 
{
    if (self.zoomScale > MinScale) {
        [self setZoomScale:MinScale animated:YES];
    } else {
        CGPoint touchPoint = [gestureRecognizer locationInView:self.imageView];
        CGFloat newZoomScale = self.maximumZoomScale;
        CGFloat xsize = self.frame.size.width/newZoomScale;
        CGFloat ysize = self.frame.size.height/newZoomScale;
        [self zoomToRect:CGRectMake(touchPoint.x - xsize/2, touchPoint.y - ysize/2, xsize, ysize) animated:YES];
    }
}

//长按
-(void)imglongTapClick:(UILongPressGestureRecognizer*)gesture
{
    if(gesture.state == UIGestureRecognizerStateBegan){
        [self discriminateCodeFromImage];
    }else if (gesture.state == UIGestureRecognizerStateEnded){
        [self showBottomAlertView];
    }
}


//识别图片中是否有二维码
- (BOOL)discriminateCodeFromImage
{
    BOOL ishaveCode;
    UIImage *image = self.imageView.image;
    CIImage *cii = [CIImage imageWithCGImage:[image CGImage]];
    CIContext *context = [CIContext contextWithOptions:nil];
    NSDictionary *detectorOptions = @{CIDetectorAccuracy : CIDetectorAccuracyHigh};
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:detectorOptions];
    NSArray *features = [detector featuresInImage:cii];
    CIQRCodeFeature *codeFeature = [features firstObject];
    if (!codeFeature.messageString.length) {
        ishaveCode = NO;
        self.codeStr = nil;
    }else{
        ishaveCode = YES;
        self.codeStr = codeFeature.messageString;
    }
    return ishaveCode;
}

- (void)showBottomAlertView
{
    @weakify(self);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"是否保存至相册", nil) message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *saveAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"保存图片", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        if([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized){
            [self saveImageToPhoto];
        }else{
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if(status == PHAuthorizationStatusAuthorized){
                    [self saveImageToPhoto];
                }
            }];
        }
    }];
    [alert addAction:saveAction];
    if(self.codeStr){
        UIAlertAction *erCodeAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"识别二维码", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            @strongify(self);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"KScanQRcode" object:self->_codeStr];
        }];
        [alert addAction:erCodeAction];
    }
    UIAlertAction *canelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:canelAction];
    [[CommUtls getCurrentVC] presentViewController:alert animated:YES completion:nil];
}

- (void)saveImageToPhoto
{
    NSData *imageData;
    if(UIImagePNGRepresentation(self.imageView.image)){
        imageData = UIImagePNGRepresentation(self.imageView.image);
    }else{
        imageData = UIImageJPEGRepresentation(self.imageView.image,1.0);
    }
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [[PHAssetCreationRequest creationRequestForAsset] addResourceWithType:PHAssetResourceTypePhoto data:imageData options:nil];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if(error){
                [HYHub showMessage:NSLocalizedString(@"保存失败", nil)];
            }else
            {
                [HYHub showMessage:NSLocalizedString(@"保存成功", nil)];
            }
        });
    }];
}

@end
